import io
import sys

import qrcode
from PySide6 import QtWidgets, QtGui
from PySide6.QtWidgets import (QApplication, QGridLayout, QLabel, QLineEdit, QPushButton, QFileDialog)


class QRCodeGenerator(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("二维码生成器")
        self.setFixedSize(400, 300)
        self.layout = QGridLayout()

        # 输入框和按钮
        self.label = QLabel("输入内容:")
        self.input_field = QLineEdit()
        self.generate_button = QPushButton("生成二维码")
        self.save_button = QPushButton("保存二维码")
        self.qr_display = QLabel()
        self.qr_display.setScaledContents(True)
        self.qr_display.setFixedSize(200, 200)

        # 布局设置
        self.layout.addWidget(self.label, 0, 0)
        self.layout.addWidget(self.input_field, 0, 1)
        self.layout.addWidget(self.generate_button, 1, 0)
        self.layout.addWidget(self.save_button, 1, 1)
        self.layout.addWidget(self.qr_display, 2, 0, 1, 2)
        self.setLayout(self.layout)

        # 信号连接
        self.generate_button.clicked.connect(self.generate_qr_code)
        self.save_button.clicked.connect(self.save_qr_code)

    def generate_qr_code(self):
        content = self.input_field.text()
        if not content:
            return

        qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
        )
        qr.add_data(content)
        qr.make(fit=True)

        img = qr.make_image(fill_color="black", back_color="white")

        # 转换为QPixmap显示
        buffer = io.BytesIO()
        img.save(buffer, format="PNG")
        qimage = QtGui.QImage.fromData(buffer.getvalue())
        pixmap = QtGui.QPixmap.fromImage(qimage)

        self.qr_display.setPixmap(pixmap)

    def save_qr_code(self):
        filename, _ = QFileDialog.getSaveFileName(self, "保存二维码", "", "PNG Files (*.png)")
        if filename:
            pixmap = self.qr_display.pixmap()
            pixmap.save(filename)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = QRCodeGenerator()
    window.show()
    sys.exit(app.exec())